<template>
  <div>
    <Upload
      v-model:file-list="fileList"
      action=""
      list-type="picture-card"
      @preview="handlePreview"
      :before-upload="beforeUpload"
      @remove="handleRemove"
      accept=".jpg,.jpeg,.gif,.png,.webp"
    >
      <div v-if="fileList.length < props.maxPic">
        <plus-outlined />
        <div style="margin-top: 8px">上传</div>
      </div>
    </Upload>
    <ImagePreview :imageList="imgList" />
  </div>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';
  export default defineComponent({
    name: 'UploadImg',
    inheritAttrs: false,
  });
</script>

<script lang="ts" setup>
  import { computed, unref, ref, watch } from 'vue';
  import { Button, Tag, Avatar, Upload, Image } from 'ant-design-vue';
  import { PictureOutlined } from '@ant-design/icons-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import type { UploadProps } from 'ant-design-vue';
  import { buttonProps } from './props';
  import { useAttrs } from '/@/hooks/core/useAttrs';
  import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { FileItem } from '/@/components/Upload/src/typing';
  import { uploadImage } from '/@/api/sys/upload';

  const globSetting = useGlobSetting();
  const { createMessage, createErrorModal } = useMessage();
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();
  const tk = userStore.getToken;

  const props = defineProps(buttonProps);
  // get component class
  const attrs = useAttrs({ excludeDefaultKeys: false });
  const getButtonClass = computed(() => {
    const { color, disabled } = props;
    return [
      {
        [`ant-btn-${color}`]: !!color,
        [`is-disabled`]: disabled,
      },
    ];
  });

  const fileList = ref<UploadProps['fileList']>([]);

  watch(
    () => props.picList,
    (value) => {
      fileList.value = [];
      if (value) {
        value.forEach((ele) => {
          fileList.value.push({
            uid: ele,
            name: ele,
            // url: `${globSetting.apiBaseUrl}/api/v1/images/${ele}?access_token=${tk}`,
            url: `${globSetting.apiBaseUrl}/api/v1/images-yt/${ele}?access_token=${tk}`,
          });
        });
      }

      props.onChange(fileList.value);
    },
    { flush: 'post' },
  );

  const imgList: string[] = [];

  function getBase64(file: File) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

  const handlePreview = async (file: UploadProps['fileList'][number]) => {
    if (!file.url && !file.preview) {
      file.preview = (await getBase64(file.originFileObj)) as string;
    }
    const onImgLoad = ({ index, url, dom }) => {
      console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
    };
    imgList.length = 0;
    imgList.push(file.url || file.preview);
    // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
    createImgPreview({ imageList: imgList, defaultWidth: 700, rememberState: true, onImgLoad });
  };

  const handleRemove: UploadProps['onRemove'] = (file) => {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;

    props.onChange(fileList.value);
  };

  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    fileList.value = [...fileList.value, file];
    props.onChange(fileList.value);
    return false;
  };

  // get inherit binding value
  const getBindValue = computed(() => ({ ...unref(attrs), ...props }));
</script>
